package org.kzwl.comm.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.GetObjectRequest;
import com.aliyun.oss.model.OSSObject;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import org.apache.pdfbox.pdfparser.PDFParser;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDDocumentInformation;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.documentinterchange.logicalstructure.PDStructureElement;
import org.apache.pdfbox.pdmodel.graphics.color.PDColor;
import org.apache.pdfbox.pdmodel.interactive.action.PDAction;
import org.apache.pdfbox.pdmodel.interactive.action.PDActionGoTo;
import org.apache.pdfbox.pdmodel.interactive.documentnavigation.destination.PDDestination;
import org.apache.pdfbox.pdmodel.interactive.documentnavigation.destination.PDPageDestination;
import org.apache.pdfbox.pdmodel.interactive.documentnavigation.outline.PDDocumentOutline;
import org.apache.pdfbox.pdmodel.interactive.documentnavigation.outline.PDOutlineItem;
import org.apache.pdfbox.pdmodel.interactive.documentnavigation.outline.PDOutlineNode;
import org.apache.pdfbox.text.PDFTextStripper;
import org.kzwl.comm.advice.BizException;
import org.kzwl.comm.advice.Consts;
import org.kzwl.comm.pojo.dto.book.BookCategoryDTO;
import org.springframework.util.DigestUtils;
import org.apache.pdfbox.io.RandomAccessBuffer;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class MyUtils {

    /**
     * 通过jwt字符串获得用户id
     *
     * @param data
     * @return
     */
    public static Integer getUserId(String data) {
        String token = JWT.decode(data).getAudience().get(0);
        JSONObject jsonObject = JSON.parseObject(token);
        String uid = jsonObject.getString("cuUserId");
        return Integer.valueOf(uid);
    }


    public static Integer getAdminUserId(String data) {
        String token = JWT.decode(data).getAudience().get(0);
        JSONObject jsonObject = JSON.parseObject(token);
        String uid = jsonObject.getString("htAdminId");
        return Integer.valueOf(uid);
    }
//
//    public static String getOrderCode() {
//        return (DateUtil.now() + getRandomCode()).replace("-", "").replace(" ", "").replace(":", "");
//    }

    public static String createMd5(String pwd) {
        return DigestUtils.md5DigestAsHex(pwd.getBytes());
    }

    public static String createJwt(String json) {
        String jwt = JWT.create().withAudience(json).sign(Algorithm.HMAC256(Consts.JwtToken.SECRETKEY));
        return jwt;
    }

    public static Integer getRandomCode() {
        Integer random = (int) ((Math.random() * 9 + 1) * 100000);
        return random;
    }

    public static List<BookCategoryDTO> getCategoryDTO(String bookName) {
        List<BookCategoryDTO> list = new ArrayList<>();
        try {
            FileInputStream fis = null;
            File file = null;
            file = new File(Consts.MyConsts.PDFPATH + bookName);
            fis = new FileInputStream(file);
            PDFParser parser = new PDFParser(new RandomAccessBuffer(fis));
            PDDocument doc = null;
            parser.parse();
            doc = parser.getPDDocument();
            PDDocumentOutline outline = doc.getDocumentCatalog().getDocumentOutline();
            if (outline != null) {
                list = MyUtils.printBookmarks(outline, "");
                System.out.println(JSONObject.toJSONString(list));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return list;
    }

    public static List<BookCategoryDTO> printBookmarks(PDOutlineNode bookmark, String indentation) throws IOException {
        PDOutlineItem current = bookmark.getFirstChild();
        List<BookCategoryDTO> list = new ArrayList<>();
        while (current != null) {
            int pages = 0;
            if (current.getDestination() instanceof PDPageDestination) {
                PDPageDestination pd = (PDPageDestination) current.getDestination();
                pages = pd.retrievePageNumber() + 1;
            }
            if (current.getAction() instanceof PDActionGoTo) {
                PDActionGoTo gta = (PDActionGoTo) current.getAction();
                if (gta.getDestination() instanceof PDPageDestination) {
                    PDPageDestination pd = (PDPageDestination) gta.getDestination();
                    pages = pd.retrievePageNumber() + 1;
                }
            }
            BookCategoryDTO dto = new BookCategoryDTO();
//            String uuid = UUID.randomUUID().toString();
            if (pages == 0) {
                System.out.println("title1-----------------------------" + indentation + current.getTitle());
            } else {
//                System.out.println(indentation + current.getTitle() + "  " + pages);
                dto.setCuBookCategoryName(current.getTitle());
                dto.setCuBookContinue(pages);
//                dto.setCuBookCategoryText(uuid);
            }
            List<BookCategoryDTO> list1 = printBookmarks(current, "    ");
            dto.getCh().addAll(list1);
            list.add(dto);
            current = current.getNextSibling();
        }
        return list;
    }

    public static void main(String[] args) throws IOException {
//        String path = "http://62.234.20.156:9000/social/A2016212.pdf";
//        //region
//        URL url = null;
//        url = new URL(path);
//        URLConnection urlConnection = url.openConnection();
//        HttpURLConnection httpURLConnection = (HttpURLConnection) urlConnection;
//        //设置超时
//        httpURLConnection.setConnectTimeout(1000 * 5);
//        //设置请求方式，默认是GET
//        httpURLConnection.setRequestMethod("POST");
//        // 设置字符编码
//        httpURLConnection.setRequestProperty("Charset", "UTF-8");
//        httpURLConnection.setRequestMethod("GET");
//        httpURLConnection.connect();
//        // 文件大小
//        int fileLength = httpURLConnection.getContentLength();
//        URLConnection con = url.openConnection();
//
//        BufferedInputStream bin = new BufferedInputStream(httpURLConnection.getInputStream());
//        // 指定文件名称(有需求可以自定义)
//        String fileFullName = UUID.randomUUID().toString();
//        // 指定存放位置(有需求可以自定义)
//        System.out.println(File.separatorChar);
//        path = Consts.MyConsts.GifPath + File.separatorChar + fileFullName;
//        file = new File(path);
//        // 校验文件夹目录是否存在，不存在就创建一个目录
//        if (!file.getParentFile().exists()) {
//            file.getParentFile().mkdirs();
//        }

//        OutputStream out = new FileOutputStream(file);
//        int len = 0;
//        byte[] buf = new byte[2048];
//        int size2 = 0;
//        while ((size2 = bin.read(buf)) != -1) {
//            len += size2;
//            out.write(buf, 0, size2);
//            // 控制台打印文件下载的百分比情况
////            System.out.println("下载了-------> " + len * 100 / fileLength + "%\n");
//        }
//        // 关闭资源
//        bin.close();
//        out.close();
        //endregion
//        try {
//            FileInputStream fis = null;
//            File file = null;
//            file = new File("C:\\Users\\Administrator\\Desktop\\pdf\\A2007039.pdf");
//            fis = new FileInputStream(file);
//            PDFParser parser = new PDFParser(new RandomAccessBuffer(fis));
//            PDDocument doc = null;
//            parser.parse();
//            doc = parser.getPDDocument();
//            // 读文本内容
//            PDFTextStripper stripper = new PDFTextStripper();
//            // 设置按顺序输出
//            stripper.setSortByPosition(true);
//            stripper.setStartPage(1);
//            stripper.setEndPage(1);
//            String content = stripper.getText(doc);
//            String trim = content.trim().replace(" ", "");
//            //出版社
//            String press = trim.substring(trim.length(), trim.lastIndexOf('\n') + 1);
//            String bookName = trim.substring(0, trim.indexOf('\n'));
////            System.out.println(trim);
//            PDDocumentInformation docInfo = doc.getDocumentInformation();
//            System.out.println("作者" + docInfo.getCreator());
//            System.out.println("出版社" + press);
//            System.out.println("书名" + bookName);
//            System.out.println("摘要" + docInfo.getSubject());
//            System.out.println("关键词" + docInfo.getKeywords());
//            System.out.println("路径" + file.getName());
//            PDDocumentOutline outline = doc.getDocumentCatalog().getDocumentOutline();
//            if (outline != null) {
//                List<BookCategoryDTO> list = MyUtils.printBookmarks(outline, "");
//                System.out.println(JSONObject.toJSONString(list));
//            }
//            doc.close();
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        MyUtils.sendSms("18238817862","123456");
    }

    public static List<File> readfile(String filepath) {
        List<File> list = new ArrayList<>();
        try {
            File file = new File(filepath);
            if (!file.isDirectory()) {
                System.out.println("文件");
                System.out.println("path=" + file.getPath());
                System.out.println("absolutepath=" + file.getAbsolutePath());
                System.out.println("name=" + file.getName());

            } else if (file.isDirectory()) {
                System.out.println("文件夹");
                String[] filelist = file.list();
                for (int i = 0; i < filelist.length; i++) {
                    File readfile = new File(filepath + "\\" + filelist[i]);
                    if (!readfile.isDirectory()) {
                        list.add(readfile);
                        System.out.println("path=" + readfile.getPath());
                        System.out.println("absolutepath=" + readfile.getAbsolutePath());
                        System.out.println("name=" + readfile.getName());

                    } else if (readfile.isDirectory()) {
                        readfile(filepath + "\\" + filelist[i]);
                    }
                }

            }

        } catch (Exception e) {
            System.out.println("readfile()   Exception:" + e.getMessage());
        }
        return list;
    }

    public static void sendSms(String phone, String param, String code) {
        System.setProperty("sun.net.client.defaultConnectTimeout", "10000");
        System.setProperty("sun.net.client.defaultReadTimeout", "10000");

        //初始化acsClient,暂不支持region化
        IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", Consts.AliYun.ACCESSKEYID, Consts.AliYun.ACCESSSECRET);
        try {
            DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", "Dysmsapi", "dysmsapi.aliyuncs.com");
        } catch (ClientException e) {
            e.printStackTrace();
        }
        IAcsClient acsClient = new DefaultAcsClient(profile);
        //组装请求对象-具体描述见控制台-文档部分内容
        SendSmsRequest request = new SendSmsRequest();
        //必填:待发送手机号
        request.setPhoneNumbers(phone);
        //必填:短信签名-可在短信控制台中找到
        request.setSignName("洛阳空中网络科技有限公司");
        //必填:短信模板-可在短信控制台中找到
        request.setTemplateCode(code);
        //可选:模板中的变量替换JSON串,如模板内容为"亲爱的${name},您的验证码为${code}"
        request.setTemplateParam(param);


        //选填-上行短信扩展码(无特殊需求用户请忽略此字段)
        //request.setSmsUpExtendCode("90997");

        //可选:outId为提供给业务方扩展字段,最终在短信回执消息中将此值带回给调用者
        // request.setOutId("yourOutId");

        //hint 此处可能会抛出异常，注意catch
        try {
            SendSmsResponse sendSmsResponse = acsClient.getAcsResponse(request);
            System.out.println(sendSmsResponse);
            if (!sendSmsResponse.getCode().equals("OK")) {
                System.err.println("短信服务异常,请联系管理员:" + JSONObject.toJSONString(sendSmsResponse));
                throw new BizException("短信服务异常,请联系管理员");
            }
        } catch (ClientException e) {
            e.printStackTrace();
        }
    }

    public static String regExHtml(String count) {
        // 过滤script标签
        StringBuffer sb = new StringBuffer(count);
        Pattern p_script = Pattern.compile(Consts.HtmlRegex.regEx_script, Pattern.CASE_INSENSITIVE);
        Matcher m_script = p_script.matcher(sb);
        sb = new StringBuffer(m_script.replaceAll(""));

        //过滤style标签
        Pattern p_style = Pattern.compile(Consts.HtmlRegex.regEx_style, Pattern.CASE_INSENSITIVE);
        Matcher m_style = p_style.matcher(sb);
        sb = new StringBuffer(m_style.replaceAll(""));

        // 过滤html标签
        Pattern p_html = Pattern.compile(Consts.HtmlRegex.regEx_html, Pattern.CASE_INSENSITIVE);
        Matcher m_html = p_html.matcher(sb);
        sb = new StringBuffer(m_html.replaceAll(""));

        // 过滤其它标签
        Pattern p_cont1 = Pattern.compile(Consts.HtmlRegex.regEx_cont1, Pattern.CASE_INSENSITIVE);
        Matcher m_cont1 = p_cont1.matcher(sb);
        sb = new StringBuffer(m_cont1.replaceAll(""));

        // 过滤html标签
//        Pattern p_cont2 = Pattern.compile(Consts.HtmlRegex.regEx_cont2, Pattern.CASE_INSENSITIVE);
//        Matcher m_cont2 = p_cont2.matcher(sb);
//        sb = new StringBuffer(m_cont2.replaceAll(""));
        return sb.toString().replaceAll("nbsp","");
    }

    public static String syncImages(String s, String unix) {
        // Endpoint以杭州为例，其它Region请按实际情况填写。
        String endpoint = "http://oss-cn-shenzhen.aliyuncs.com";
// 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, Consts.AliYun.ACCESSKEYID, Consts.AliYun.ACCESSSECRET);

// ossObject包含文件所在的存储空间名称、文件名称、文件元信息以及一个输入流。
        String name =  unix + ".jpg";
        String imgUrl = null;
        try {
            File file = new File(Consts.AliYun.LocalFilePath + unix + ".jpg");
            ossClient.getObject(new GetObjectRequest(Consts.AliYun.IMAGESBUCKET, s + ".jpg"),file );
            // 上传Byte数组。
            FileInputStream fis = new FileInputStream(file);
            ByteArrayOutputStream bos = new ByteArrayOutputStream(1000);
            byte[] b = new byte[1024];
            int len = -1;
            while((len = fis.read(b)) != -1) {
                bos.write(b, 0, len);
            }
            byte[] fileByte = bos.toByteArray();
            PutObjectRequest putObjectRequest = new PutObjectRequest(Consts.AliYun.IMAGESBUCKET, name, new ByteArrayInputStream(fileByte));
            ossClient.putObject(putObjectRequest);
//            ossClient.putObject(Consts.AliYun.IMAGESBUCKET, name, new ByteArrayInputStream(bytes));
             imgUrl = Consts.AliYun.IMAGESBUCKETURL+name;
            System.out.println(imgUrl);
        } catch (Exception e) {
            e.printStackTrace();
        }
// 数据读取完成后，获取的流必须关闭，否则会造成连接泄漏，导致请求无连接可用，程序无法正常工作。

// 关闭OSSClient。
        ossClient.shutdown();
        return imgUrl;
    }
}
